# coding:utf-8

from flask import jsonify
from flask import request

from .. import db
from ..base import base
from ..models.URLGenerate import URLGenerate


@base.route('/shotUrl/addUrl', methods=['GET'])
def add_url():
    data = request.json
    id = data.get('id')
    long_url = data.get('long_url')
    short_url = data.get('short_url')

    if not long_url or not short_url:
        return jsonify({'error': 'Missing data'}), 400
    try:
        if 'id' not in data or data['id'] == 0:
            # 插入操作
            url = URLGenerate(long_url=long_url, short_url=short_url)
            db.session.add(url)
        else:
            # 更新操作
            url = URLGenerate.query.get(id)
            if url:
                url.long_url = long_url
                url.short_url = short_url
            else:
                return jsonify({'error': 'ID not found'}), 404

        db.session.commit()
        return jsonify(url.to_json()), 200 if id else 201
    except Exception as e:
        db.session.rollback()
    return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500


@base.route('/shotUrl/getList', methods=['GET'])
def get_urls():
    """获取所有 URL 记录的列表，支持排序和过滤"""
    short_url_query = request.args.get('short_url')
    try:
        query = URLGenerate.query

        # 过滤短链接
        if short_url_query:
            query = query.filter(URLGenerate.short_url.like(f'%{short_url_query}%'))

        # 按 id 倒序排序
        urls = query.order_by(URLGenerate.id.desc()).all()

        return jsonify([url.to_json() for url in urls])
    except Exception as e:
        return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
